<?php

namespace mbilling\BillingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

use mbilling\BillingBundle\Model\BonusesTableModel;
use mbilling\BillingBundle\Model\BonusesModel;
use mbilling\BillingBundle\Model\UsersModel;
use mbilling\BillingBundle\Model\UsersAdminLogsModel;
use mbilling\BillingBundle\Entity\bonusesTable;
use mbilling\BillingBundle\Entity\usersAdminLogs;

use mbilling\BillingBundle\Form\BonusesTableForm;

class BonusesTableController extends Controller
{
    public function indexAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bonusTable_model = new BonusesTableModel($em);
        $user_model = new UsersModel($em);
        $bonus_model = new BonusesModel($em);
        
        $bonusesTable = $bonusTable_model->findAll();
        $users_string = array();
        $bonus_string = array();

        $dir=opendir(dirName('../'.basename(__FILE__)).'/vendor/mpanel/classes/Bonuses/');
        $file_string = array();
        while ($file = readdir($dir))
        {
            if (in_array($file,array('.','..')))
                continue;
            $expl=explode('.', $file);
            $expl_size=sizeof($expl);
            if (mb_strtolower($expl[$expl_size-1],'UTF-8') != 'php')
                continue;
            $file_len = sizeof($file_string);
            $file_string[$file_len] = $file;
        }
        closedir($dir);
        array_multisort($file_string);
        $names = array();
        $coupon_string = array();
        foreach($file_string as $coupon)
        {
            $expl=explode('.', $coupon);
            $class_name = $expl['0'];
            $class_name = 'Bonuses_'.$class_name;
            $check_domain = $this->get('check_domain');
            $class = $class_name::newInstance(NULL, NULL, NULL, $check_domain, $em);
            array_push($names, $class_name);
            array_push($coupon_string, $class->getTitle());
        }
        
        foreach($bonusesTable as $bonusTable)
        {
            $user = $user_model->findByPK($bonusTable->getUserId());
            $users_string[$bonusTable->getId()] = $user->getLogin();

            $bonus = $bonus_model->findByPK($bonusTable->getBonusId());
            if ($bonus->getCoupon() == 'no')
                $bonus_string[$bonusTable->getId()] = 'Бонус "'.$bonus->getName().'"';
            else
            {
                foreach($names as $key => $name)
                {
                    if ($name == $bonus->getCoupon())
                    {
                        $bonus_string[$bonusTable->getId()] = 'Бонус "'.$bonus->getName().'" + '.$coupon_string[$key];
                    }
                }
            }
        }
        return $this->render('BillingBundle:Bonuses_table:index.html.twig', array('bonusesTable' => $bonusesTable, 'users' => $users_string, 'bonuses' => $bonus_string));
    }
    public function addAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bonusTable_model = new BonusesTableModel($em);
        $user_model = new UsersModel($em);
        $bonus_model = new BonusesModel($em);
        
        $bonusTable = new bonusesTable();
        //$bonusTable_model->create($bonusTable->initDefaultEntity());
        //return new RedirectResponse($this->generateUrl('bonuses_table_show'));
        
        $users_string = array();
        $users = $user_model->findAll();
        foreach($users as $user)
        {
            $users_string[$user->getId()] = $user->getLogin();
        }
        $bonus_string = array();
        $bonuses = $bonus_model->findAll();

        $dir=opendir(dirName('../'.basename(__FILE__)).'/vendor/mpanel/classes/Bonuses/');
        $file_string = array();
        while ($file = readdir($dir))
        {
            if (in_array($file,array('.','..')))
                continue;
            $expl=explode('.', $file);
            $expl_size=sizeof($expl);
            if (mb_strtolower($expl[$expl_size-1],'UTF-8') != 'php')
                continue;
            $file_len = sizeof($file_string);
            $file_string[$file_len] = $file;
        }
        closedir($dir);
        array_multisort($file_string);
        $names = array();
        $coupon_string = array();
        foreach($file_string as $coupon)
        {
            $expl=explode('.', $coupon);
            $class_name = $expl['0'];
            $class_name = 'Bonuses_'.$class_name;
            $check_domain = $this->get('check_domain');
            $class = $class_name::newInstance(NULL, NULL, NULL, $check_domain, $em);
            array_push($names, $class_name);
            array_push($coupon_string, $class->getTitle());
        }
        
        foreach($bonuses as $bonus)
        { 
            if ($bonus->getCoupon() == 'no')
                $bonus_string[$bonus->getId()] = 'Бонус "'.$bonus->getName().'"';
            else
            {
                foreach($names as $key => $name)
                {
                    if ($name == $bonus->getCoupon())
                    {
                        $bonus_string[$bonus->getId()] = 'Бонус "'.$bonus->getName().'" + '.$coupon_string[$key];
                    }
                }
            }
            if (!$bonus->getIsActive())
                $bonus_string[$bonus->getId()] .= '(не активен)';
        }
        $errors = array();
        if (count($bonus_string) == 0)
            array_push($errors, array('message' => 'Бонусы не созданы!', 'link' => 'bonuses_add'));
        if (count($errors) != 0)
        {
            return $this->render('BillingBundle:Bonuses_table:error.html.twig', array('errors' => $errors));
        }
        $form = $this->createForm(new BonusesTableForm($users_string, $bonus_string), $bonusTable);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $bonusTable_model->create($form->getData());

                $securityContext = $this->container->get('security.context');
                $userCurrent = $securityContext->getToken()->getUser();
                $log_model = new UsersAdminLogsModel($em);
                $log = new usersAdminLogs();
                $log->setAdminId($userCurrent->getId());
                $log->setPageId('16');//страница список выданных бонусов
                $log->setObjectId($bonusTable->getId());//изменяемый объект
                $log->setActionTypeId('1');//создание выданного бонуса
                $log_model->create($log);
                return new RedirectResponse($this->generateUrl('bonuses_table_show'));
            }
        }
        return $this->render('BillingBundle:Bonuses_table:create.html.twig', array('form' => $form->createView()));
    }
    public function updateAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bonusTable_model = new BonusesTableModel($em);
        $user_model = new UsersModel($em);
        $bonus_model = new BonusesModel($em);
        
        $bonusTable = $bonusTable_model->findByPK($id);
        
        $users_string = array();
        $users = $user_model->findAll();
        foreach($users as $user)
        {
            $users_string[$user->getId()] = $user->getLogin();
        }
        $bonus_string = array();
        $bonuses = $bonus_model->findAll();

        $dir=opendir(dirName('../'.basename(__FILE__)).'/vendor/mpanel/classes/Bonuses/');
        $file_string = array();
        while ($file = readdir($dir))
        {
            if (in_array($file,array('.','..')))
                continue;
            $expl=explode('.', $file);
            $expl_size=sizeof($expl);
            if (mb_strtolower($expl[$expl_size-1],'UTF-8') != 'php')
                continue;
            $file_len = sizeof($file_string);
            $file_string[$file_len] = $file;
        }
        closedir($dir);
        array_multisort($file_string);
        $names = array();
        $coupon_string = array();
        foreach($file_string as $coupon)
        {
            $expl=explode('.', $coupon);
            $class_name = $expl['0'];
            $class_name = 'Bonuses_'.$class_name;
            $check_domain = $this->get('check_domain');
            $class = $class_name::newInstance(NULL, NULL, NULL, $check_domain, $em);
            array_push($names, $class_name);
            array_push($coupon_string, $class->getTitle());
        }
        
        foreach($bonuses as $bonus)
        {
            if ($bonus->getCoupon() == 'no')
                $bonus_string[$bonus->getId()] = 'Бонус "'.$bonus->getName().'"';
            else
            {
                foreach($names as $key => $name)
                {
                    if ($name == $bonus->getCoupon())
                    {
                        $bonus_string[$bonus->getId()] = 'Бонус "'.$bonus->getName().'" + '.$coupon_string[$key];
                    }
                }
            }
            if (!$bonus->getIsActive())
                $bonus_string[$bonus->getId()] .= '(не активен)';
        }
        $errors = array();
        if (count($bonus_string) == 0)
            array_push($errors, array('message' => 'Бонусы не созданы!', 'link' => 'bonuses_add'));
        if (count($errors) != 0)
        {
            return $this->render('BillingBundle:Bonuses_table:error.html.twig', array('errors' => $errors));
        }
        $form = $this->createForm(new BonusesTableForm($users_string, $bonus_string), $bonusTable);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $bonusTable_model->create($form->getData());

                $securityContext = $this->container->get('security.context');
                $userCurrent = $securityContext->getToken()->getUser();
                $log_model = new UsersAdminLogsModel($em);
                $log = new usersAdminLogs();
                $log->setAdminId($userCurrent->getId());
                $log->setPageId('16');//страница список выданных бонусов
                $log->setObjectId($bonusTable->getId());//изменяемый объект
                $log->setActionTypeId('2');//изменение выданного бонуса
                $log_model->create($log);
                return new RedirectResponse($this->generateUrl('bonuses_table_show'));
            }
        }
        return $this->render('BillingBundle:Bonuses_table:create.html.twig', array('form' => $form->createView()));
    }
    public function removeAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bonusTable_model = new BonusesTableModel($em);

        $bonusTable = $bonusTable_model->findByPK($id);
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $bonusTable_model->removeByPK($id);

        $log_model = new UsersAdminLogsModel($em);
        $log = new usersAdminLogs();
        $log->setAdminId($userCurrent->getId());
        $log->setPageId('16');//страница список выданных бонусов
        $log->setObjectId($id);//изменяемый объект
        $log->setActionTypeId('3');//удаление выданного бонуса
        $log_model->create($log);

        return new RedirectResponse($this->generateUrl('bonuses_table_show'));
    }
    public function renderInfoAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        if ($userCurrent == 'anon.')
        {
            return new Response('');
        }
        $bonusTable_model = new BonusesTableModel($em);
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $bonusesTable = $bonusTable_model->findByUserIdAndActive($this->get('session')->get('user')->getId(), '1');
        else
            $bonusesTable = $bonusTable_model->findByUserIdAndActive($userCurrent->getId(), '1');
        return $this->render('BillingBundle:Bonuses_table:info.html.twig', array('count' => count($bonusesTable)));
    }
}